package cn.agiledata.bank.myspace.action;

import java.math.BigDecimal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.hibernateBean.Account;
import cn.agiledata.bank.scores.service.IScoresService;
import cn.agiledata.bank.scores.service.ScoresFactory;
import com.vnv.infrastructure.exception.IPBException;

public class LotteryAction extends AbstractMySpaceAction {
	
	/**
	 * 抽奖
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws IPBException
	 * @throws Exception
	 */
	public ActionForward lottery(ActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response) throws IPBException, Exception {
		// 抽奖商品ID
		String strPrizeId = request.getParameter("prize");
		// 抽奖积分
//		String strScore = request.getParameter("score");
		String strScore = null;
		
		if("1".equals(strPrizeId) || "2".equals(strPrizeId) || "3".equals(strPrizeId)) {
			strScore = "1000";
		}
		
		if("4".equals(strPrizeId)) {
			strScore = "700";
		}
		
		if("5".equals(strPrizeId)) {
			strScore = "500"; 
		}
		
		if("6".equals(strPrizeId) || "7".equals(strPrizeId)) {
			strScore = "100"; 
		}
		
		if("8".equals(strPrizeId)) {
			strScore = "50"; 
		}
		
		if(strScore == null) {
			request.setAttribute("warning", "不存在的抽奖项目！");
            return mapping.findForward("result");
		}
		
		double dbScore = Double.parseDouble(strScore);
		
		// 判断积分是否足够
		Account account = getAccount(request);
		if(dbScore > account.getTotalScores().doubleValue()) {
			request.setAttribute("warning", "您的积分不足");
            return mapping.findForward("result");
		}
		
		// 扣除积分
		IScoresService scoreService = ScoresFactory.getScoresService();
		//String success = scoreService.reduceScores(account,new Double(dbScore), "lottery");
		String success = scoreService.calcScores(account,new Double(-dbScore), Constant.SCORES_SOURCE_K);//抽奖的积分
		
		// 扣除积分结果显示
		if (success.equals(Constant.DEDUCE_SCORES_B)) {
            request.setAttribute("warning", "您的积分不够。");
            return mapping.findForward("result");
        }
        if (success.equals(Constant.DEDUCE_SCORES_C)) {
            request.setAttribute("warning", "您的积分没有激活，请在账户首页激活您的积分。");
            return mapping.findForward("result");
        }
        
        request.setAttribute("totalScore", new BigDecimal(account.getTotalScores().doubleValue()).toString());
        
        // 返回抽奖结果
        return mapping.findForward("result");
    }
}
